package cn.jbolt.core.gen;

import cn.hutool.core.io.FileUtil;
import cn.jbolt.core.model.Permission;
import cn.jbolt.core.util.JBoltStringUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.jfinal.template.ext.directive.NowDirective;

import java.io.File;
import java.util.List;

/**
 * 本系统中资源权限表里定义的资源
 * 快捷生成静态常量到PermissionKey.java文件中，
 * 方便其他地方统一调用
 */
public class JBoltInnerPermissionKeyGen {
	public static final String SEPARATOR=File.separator;
	public static void genToCurrentProject() {
		gen(null);
	}
	public static void gen(String projectPath) {
		//JBolt项目绝对路径 修改这个就行
		String PROJECT_PATH= StrKit.defaultIfBlank(projectPath,System.getProperty("user.dir"));
		//PermissionKey.java的绝对路径
		String TARGET=FileUtil.normalize(PROJECT_PATH+SEPARATOR+"jbolt_extend"+SEPARATOR+"src"+SEPARATOR+"main"+SEPARATOR+"java"+SEPARATOR+"cn"+SEPARATOR+"jbolt"+SEPARATOR+"extend"+SEPARATOR+"permission"+SEPARATOR+"PermissionKey.java");
		//模板绝对路径
		String TPL=FileUtil.normalize(PROJECT_PATH+SEPARATOR+"jbolt_code_generator"+SEPARATOR+"src"+SEPARATOR+"main"+SEPARATOR+"resources"+SEPARATOR+"gentpl"+SEPARATOR+"permissionkey.tpl");
		List<Permission> permissions = new Permission().dao().findAll();
		Engine engine = new Engine();
		engine.addSharedObject("JBoltStringUtil", new JBoltStringUtil());
		engine.addDirective("now",NowDirective.class,true);
//		engine.setStaticFieldExpression(true);
//		engine.setStaticMethodExpression(true);
		Template template=engine.getTemplate(TPL);
		FileUtil.writeUtf8String(template.renderToString(Kv.by("permissions", permissions)),TARGET);
	}
}
